今天就延續 part 1 沒有補到的一些小觀念
將狀態的判斷用另外一個function獨立處理
if (fetchState.state === 'fetching' && isEmpty(listNode)) {
// ...
}
function isLoading(fetchState, listNode) {
return fetchState.state === 'fetching' && isEmpty(listNode);
}
if (isLoading(fetchStateInstance, listNodeInstance)) {
// ...
}
直接看code~
function isNotRender(item) {
// ...
}
if (!isNotRender(item)) {
// ...
}
function isRender(item) {
// ...
}
if (isRender(item)) {
// ...
}
Functional Programming 會讓你的 code 更加乾淨且容易被測試。當你在寫程式時,盡量選擇此設計方式 (最常見的就是改寫不容易看的 for 迴圈)。
//Bad
var approved = []
for (var i = 0; i < approved.length; i++) {
if (users[i].score >= 70) {
approved.push(approved)
}
}
//Better
const approved = filter(user => user.score >= 70, users)
//Bad
const programmerOutput = [
{
name: 'Uncle Bobby',
linesOfCode: 500
},
{
name: 'Suzie Q',
linesOfCode: 1500
},
{
name: 'Jimmy Gosling',
linesOfCode: 150
},
{
name: 'Gracie Hopper',
linesOfCode: 1000
}
];
let totalOutput = 0;
for (let i = 0; i < programmerOutput.length; i++) {
totalOutput += programmerOutput[i].linesOfCode;
}
//Better
const programmerOutput = [
{
name: 'Uncle Bobby',
linesOfCode: 500
},
{
name: 'Suzie Q',
linesOfCode: 1500
},
{
name: 'Jimmy Gosling',
linesOfCode: 150
},
{
name: 'Gracie Hopper',
linesOfCode: 1000
}
];
const totalOutput = programmerOutput.reduce(
(totalLines, output) => totalLines + output.linesOfCode,
0
);
從例子就可以看出用 flag 作為參數時 function 就做了兩件事,那這樣就違背了我們function一次只做一件事的原則。
//Bad
function printData (data, flag){
if(flag){
console.log(`public data is ${data}`)
}else{
console.log(`private data is ${data}`)
}
}
//Better
function printPublicData (data){
console.log(`public data is ${data}`)
}
function printPrivateData (data){
cconsole.log(`private data is ${data}`)
}
function 的介紹就到此為止拉,還有其他技巧都可以參考
clean-code-javascript